//
//  SaleOutLibaryVC.m
//  New_Runway
//
//  Created by mack on 2018/1/26.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "SaleOutLibaryVC.h"
#import "BasePickView.h"
#import "PickCityView.h"
#import "PickDateView.h"
#import "PickCustomView.h"
#import "CarConfigHeaferView.h"
#import "CarSetListCell.h"

#import "CarBaseInfoModel.h"
#import "UserModel.h"
#import "CustomersModel.h"
#import "SafeCompanyModel.h"
#import "MortgageCompanyModel.h"
#import "AVCaptureViewController.h"

@interface SaleOutLibaryVC ()<PickerDateViewDelegate,PickerCityViewDelegate,CustomPickViewDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    BOOL isShowDay;//是否显示日信息
    BOOL isSel;
    NSString *_selaStr;
    NSString *_dateStr;
    NSString *_peopleName;
    NSString *_peopleId;
    NSString *_customer;
    NSString *_customerId;
    NSString *_adress;
    NSString *_company;
    NSString *_companyID;
    NSString *_dealPrice;//成交价
    NSString *_orderPrice;//定金
    NSString *_remarks;//备注
    NSString *_phoneNum;//手机号
    NSString *_customName;//客户名称
    NSString *_Idcard;//证件号
    NSString *_business;//商业险
    NSString *_strong;//交强险
    NSString *_prevince;
    NSString *_previnceId;
    NSString *_city;
    NSString *_cityId;
    
//    NSString *_orderPrice1;//定金
    NSString *_balance;//余款
    NSString *_transferFee;//过户费
    NSString *_commission;//佣金
    NSString *_billingCost;//开票费用
    NSString *_otherCost;//其他费用
    NSString *_mortgage;//按揭公司
    NSString *_mortgageId;//按揭公司id
    
    NSString *_firstPrice;//首付款
    NSString *_loanLimit;//贷款额度
    NSString *_mortgageCyc;//按揭周期
    NSString *_mortgagePrice;//按揭费用
    NSString *_deposit;//押金
    
    
    
}
@property(nonatomic, strong) UITableView *tableview;
@property (nonatomic, assign) BOOL isPayType;//yes 按揭 no现金
@property(nonatomic, strong) NSMutableArray *userArray;
@property(nonatomic, strong) NSMutableArray *customerArray;
@property(nonatomic, strong) NSMutableArray *safeComArray;
@property(nonatomic, strong) NSMutableArray *mortgageComArray;

@property (nonatomic, strong) CarBaseInfoModel *infomodel;


@end

@implementation SaleOutLibaryVC

-(NSMutableArray *)userArray{
    if (!_userArray) {
        _userArray = [[NSMutableArray alloc] init];
    }
    
    return  _userArray;
}
-(NSMutableArray *)customerArray{
    if (!_customerArray) {
        _customerArray = [[NSMutableArray alloc] init];
    }
    return _customerArray;
}
-(NSMutableArray *)safeComArray{
    if (!_safeComArray) {
        _safeComArray = [[NSMutableArray alloc] init];
    }
    return _safeComArray;
}
-(NSMutableArray *)mortgageComArray{
    if (!_mortgageComArray) {
        _mortgageComArray = [[NSMutableArray alloc] init];
    }
    return _mortgageComArray;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBarView.titleLabel.text = @"销售出库";
    self.view.backgroundColor = kColorWhite();
    self.isPayType = NO;
    [self.navigationBarView.rightItem setTitle:@"确定" forState:UIControlStateNormal];
    [self setKey];
    isSel = NO;
    [self initTableview];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    self.infomodel = self.parems[@"info"];
    
}
-(void)setKey{
    
    _selaStr = _dateStr = _peopleName = _peopleId = _customer = _customerId = _adress = _company = _companyID = _dealPrice = _orderPrice = _remarks = _phoneNum = _customName = _Idcard = _business = _strong = _prevince = _previnceId = _city = _cityId  = _balance = _transferFee = _commission = _billingCost = _otherCost =  _otherCost = _mortgage  = _firstPrice = _loanLimit = _mortgageCyc = _mortgagePrice = _deposit = @"";
    _mortgageId = @"1";

}
-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.backgroundColor = MAIN_COLOR();
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableview registerClass:[CarConfigHeaferView class] forHeaderFooterViewReuseIdentifier:@"header"];
    [self.tableview registerClass:[CarSetListCell class] forCellReuseIdentifier:@"CarSetListCell"];
//    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CELL"];
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).mas_equalTo(self.navH);
        make.bottom.equalTo(weakSelf.view).mas_equalTo(-self.BotH);
        make.left.right.equalTo(weakSelf.view);
    }];
    
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 5;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 45;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 5;
    }else if (section == 1){
        if (_isPayType == YES) {
            return 7;
        }
        return 3;
    }else if (section == 2){
        return 4;
    }else if (section == 3){
        return 5;
    }
    if (isSel == YES) {
        return 4;
    }else{
        
        return 1;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSArray *sectionOnes = @[@"销售类型",@"成交日期",@"成交员工",@"成交价格",@"备注"];
    NSArray *sectionTwos = @[@"联系电话",@"客户名称",@"客户来源",@"归属地",@"证件号"];
    NSArray *sectionThrees = @[@"是否代办保险",@"保险公司",@"商业险",@"交强险"];
    NSArray *sectionFives = @[@"过户费用",@"佣金",@"开票费用",@"其他费用"];
    CarSetListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CarSetListCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    cell.centerTF.delegate = self;
    cell.switchButton.hidden = YES;
    cell.centerTF.returnKeyType = UIReturnKeyDone;
    cell.StarL.hidden =YES;

    if (indexPath.section == 0) {
        cell.centerTF.tag = indexPath.row;
        cell.label.text = sectionOnes[indexPath.row];
        if ( indexPath.row == 3 ) {
            
            cell.centerTF.placeholder = @"请填写成交价格";
            cell.centerTF.keyboardType = UIKeyboardTypeDecimalPad;
            cell.centerLabel.hidden = YES;
            cell.centerTF.hidden = NO;
            [cell.rightImage setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
            [cell.rightImage setTitle:@"万元" forState:UIControlStateNormal];
        }else if( indexPath.row == 4){
            cell.centerTF.placeholder = @"请填写备注";
            cell.centerTF.keyboardType = UIKeyboardTypeDefault;
            cell.rightImage.hidden = YES;
            cell.centerLabel.hidden = YES;
            cell.centerTF.hidden = NO;
            
            
        }else{
            cell.centerLabel.hidden = NO;
            cell.centerTF.hidden = YES;
            cell.rightImage.hidden = NO;
            [cell.rightImage setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
            [cell.rightImage setTitle:@"" forState:UIControlStateNormal];
        }
      
        
        if (indexPath.row == 0) {
            cell.centerLabel.text = _selaStr;
            cell.StarL.hidden = NO;

        }else if (indexPath.row == 1){
            
            cell.centerLabel.text = _dateStr;
            cell.StarL.hidden = NO;

        }else if (indexPath.row == 2){
            cell.centerLabel.text = _peopleName;
            cell.StarL.hidden = NO;

        }else if (indexPath.row == 3){
            cell.centerTF.text = _dealPrice;
            cell.StarL.hidden = NO;

        }else if (indexPath.row == 4){
            cell.centerTF.text = _remarks;
        }
        
        
        
    }else if (indexPath.section == 1){
        
        NSArray *sectionFours;
        if (_isPayType == NO) {
           sectionFours = @[@"付款类型",@"定金",@"余款"];
        }else{
           sectionFours = @[@"付款类型",@"按揭公司",@"首付款",@"贷款额度",@"按揭周期",@"按揭费用",@"押金"];
        }
        
        cell.label.text = sectionFours[indexPath.row];
        cell.centerTF.keyboardType = UIKeyboardTypeDecimalPad;
        if (_isPayType == NO) {
            cell.centerTF.tag = [[NSString stringWithFormat:@"%zd%zd",indexPath.section,indexPath.row] integerValue];

            
            if (indexPath.row == 0) {
                
                cell.centerLabel.text = @"现金";
                
                cell.centerLabel.hidden = NO;
                cell.centerTF.hidden = YES;
                cell.rightImage.hidden = NO;
                [cell.rightImage setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
                [cell.rightImage setTitle:@"" forState:UIControlStateNormal];
                
            }else{
                
                cell.centerLabel.hidden = YES;
                cell.centerTF.hidden = NO;
                cell.rightImage.hidden = NO;
                [cell.rightImage setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
                [cell.rightImage setTitle:@"万元" forState:UIControlStateNormal];
                cell.centerTF.placeholder = @"请填写金额";
                cell.centerTF.keyboardType = UIKeyboardTypeDecimalPad;
                
                if (indexPath.row == 1) {
                    cell.centerTF.text = _orderPrice;
                }else{
                    cell.centerTF.text = _balance;

                }
                
            }
            
        }else{
            cell.centerTF.tag = [[NSString stringWithFormat:@"%zd%zd",indexPath.section,indexPath.row + 1] integerValue];
 
            if (indexPath.row == 0) {
                
                cell.centerLabel.text = @"按揭";
                cell.centerLabel.hidden = NO;
                cell.centerTF.hidden = YES;
                cell.rightImage.hidden = NO;
                [cell.rightImage setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
                [cell.rightImage setTitle:@"" forState:UIControlStateNormal];
            }else if (indexPath.row == 1){
                
                cell.centerLabel.text = _mortgage;
                cell.centerLabel.hidden = NO;
                cell.centerTF.hidden = YES;
                cell.rightImage.hidden = NO;
                [cell.rightImage setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
                [cell.rightImage setTitle:@"" forState:UIControlStateNormal];

            }else if (indexPath.row == 2){
                cell.centerLabel.hidden = YES;
                cell.centerTF.hidden = NO;
                cell.rightImage.hidden = NO;
                cell.centerTF.placeholder = @"请填写金额";
                [cell.rightImage setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
                [cell.rightImage setTitle:@"万元" forState:UIControlStateNormal];
                cell.centerTF.text = _firstPrice;
                
            }else if (indexPath.row == 3){
                cell.centerLabel.hidden = YES;
                cell.centerTF.hidden = NO;
                cell.rightImage.hidden = NO;
                cell.centerTF.placeholder = @"请填写金额";
                [cell.rightImage setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
                [cell.rightImage setTitle:@"万元" forState:UIControlStateNormal];
                cell.centerTF.text = _loanLimit;
            }else if (indexPath.row == 4){
                cell.centerLabel.hidden = YES;
                cell.centerTF.hidden = NO;
                cell.rightImage.hidden = NO;
                cell.centerTF.placeholder = @"请填写按揭周期";
                [cell.rightImage setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
                [cell.rightImage setTitle:@"月" forState:UIControlStateNormal];
                cell.centerTF.text = _mortgageCyc;
            }else if (indexPath.row == 5){
                cell.centerLabel.hidden = YES;
                cell.centerTF.hidden = NO;
                cell.rightImage.hidden = NO;
                cell.centerTF.placeholder = @"请填写金额";
                [cell.rightImage setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
                [cell.rightImage setTitle:@"元" forState:UIControlStateNormal];
                cell.centerTF.text = _mortgagePrice;
            }else if (indexPath.row == 6){
                cell.centerLabel.hidden = YES;
                cell.centerTF.hidden = NO;
                cell.rightImage.hidden = NO;
                cell.centerTF.placeholder = @"请填写金额";
                [cell.rightImage setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
                [cell.rightImage setTitle:@"元" forState:UIControlStateNormal];
                cell.centerTF.text = _deposit;
            }
            
            
        }

       
        
    }else if (indexPath.section == 2){
      
        cell.label.text = sectionFives[indexPath.row];
        cell.centerLabel.hidden = YES;
        cell.centerTF.hidden = NO;
        cell.rightImage.hidden = NO;
        [cell.rightImage setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [cell.rightImage setTitle:@"元" forState:UIControlStateNormal];
        cell.centerTF.placeholder = @"请填写金额";
        cell.centerTF.keyboardType = UIKeyboardTypeDecimalPad;
        cell.centerTF.tag = [[NSString stringWithFormat:@"%zd%zd",indexPath.section,indexPath.row] integerValue];
        if (indexPath.row == 0) {
            cell.centerTF.text = _transferFee;
        }if (indexPath.row == 1) {
             cell.centerTF.text = _commission;
        }if (indexPath.row == 2) {
             cell.centerTF.text = _billingCost;
        }if (indexPath.row == 3) {
             cell.centerTF.text = _otherCost;
        }
      
    }else if (indexPath.section == 3){
        
        
        
        cell.label.text = sectionTwos[indexPath.row];
        cell.centerTF.tag = [[NSString stringWithFormat:@"%zd%zd",indexPath.section,indexPath.row] integerValue];
        
        
        if (indexPath.row == 0 || indexPath.row == 1 ) {
            cell.rightImage.hidden = YES;
            cell.centerLabel.hidden = YES;
            cell.centerTF.hidden = NO;
            
            
        }else if (indexPath.row == 2 || indexPath.row == 3) {
            cell.centerLabel.hidden = NO;
            cell.centerTF.hidden = YES;
            cell.rightImage.hidden = NO;
            [cell.rightImage setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
            [cell.rightImage setTitle:@"" forState:UIControlStateNormal];
            
            
        }
        if (indexPath.row == 0) {
            cell.centerTF.keyboardType = UIKeyboardTypeNumberPad;
            cell.centerTF.placeholder = @"请输入11位手机号";
            cell.centerTF.text = _phoneNum;

        }else if (indexPath.row == 1){
            
            cell.centerTF.keyboardType = UIKeyboardTypeDefault;
            cell.centerTF.placeholder = @"最多输入二十个字符";
            cell.centerTF.text = _customName;

            
        }else if (indexPath.row == 2) {
            cell.centerLabel.text = _customer;
            
           
        }else if (indexPath.row == 3){
            cell.centerLabel.text = _adress;
            
        }else if (indexPath.row == 4){
            cell.rightImage.hidden = NO;
            [cell.rightImage setImage:[UIImage imageNamed:@"扫描身份证"] forState:UIControlStateNormal];
            [cell.rightImage setTitle:@"" forState:UIControlStateNormal];
            cell.centerLabel.hidden = YES;
            cell.centerTF.hidden = NO;
            cell.centerTF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
            cell.centerTF.placeholder = @"请填写证件号";
            cell.centerTF.text = _Idcard;
            
        }
        
    }else if (indexPath.section == 4){
        
        
        cell.label.text = sectionThrees[indexPath.row];
        cell.centerTF.tag = [[NSString stringWithFormat:@"%zd%zd",indexPath.section,indexPath.row] integerValue];
        if (indexPath.row == 0) {
            cell.rightImage.hidden = YES;
            cell.centerLabel.hidden = YES;
            cell.centerTF.hidden = YES;
            cell.switchButton.hidden = NO;
            [cell.switchButton setOn:isSel];
            
            
        }else if (indexPath.row == 1) {
            cell.centerLabel.hidden = NO;
            cell.centerTF.hidden = YES;
            cell.rightImage.hidden = NO;
            [cell.rightImage setImage:[UIImage imageNamed:@"up"] forState:UIControlStateNormal];
            [cell.rightImage setTitle:@"" forState:UIControlStateNormal];
            cell.centerLabel.text = _company;
            cell.centerTF.keyboardType = UIKeyboardTypeDecimalPad;
            cell.centerTF.placeholder = @"请填写商业险金额";
            
            
        }else{
            cell.centerLabel.hidden = YES;
            cell.centerTF.hidden = NO;
            cell.rightImage.hidden = NO;
            [cell.rightImage setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
            [cell.rightImage setTitle:@"元" forState:UIControlStateNormal];
            cell.centerTF.keyboardType = UIKeyboardTypeDecimalPad;
            if (indexPath.row == 2) {
                cell.centerTF.placeholder = @"请填写商业险金额";
                cell.centerTF.text = _business;

            }else{
           
                cell.centerTF.placeholder = @"请填写交强险金额";
                cell.centerTF.text = _strong;

            }
            
        }
        
        
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            
            NSMutableArray *arrayData = [NSMutableArray arrayWithObjects:@"批发",@"直销",@"拍卖", nil];
            
            [self creatChoose:arrayData tag:indexPath.row];
        }else if (indexPath.row == 1){
            
            [self CreatDateChoose];
            
        }else if (indexPath.row == 2){
            
            [self LoadStaffInfo];
        }
    }else if (indexPath.section == 1){
     
        if (_isPayType == NO) {
            if (indexPath.row == 0) {
                NSMutableArray *arrayData = [NSMutableArray arrayWithObjects:@"现金",@"按揭", nil];
                [self creatChoose:arrayData tag:5];
            }
        }else{
            if (indexPath.row == 0) {
                NSMutableArray *arrayData = [NSMutableArray arrayWithObjects:@"现金",@"按揭", nil];
                [self creatChoose:arrayData tag:5];
            }else if (indexPath.row == 1){
                
                [self laodMortgageList];

            }
        }
        
        
        
    }else if (indexPath.section == 2){
       
        
    }else if (indexPath.section == 3){
        
        if (indexPath.row == 2) {
            [self loadCustomers];
        }else if (indexPath.row == 3){
            
            [self chooseAdress];
        }else if (indexPath.row == 4){
            kSelfWeak;
            AVCaptureViewController *AVVC = [[AVCaptureViewController alloc] init];
            AVVC.cardBlock = ^(NSString *cardNum) {
                _Idcard = cardNum;
                [weakSelf.tableview reloadData];
            };
            [self.navigationController pushViewController:AVVC animated:YES];
        }
        
    }else if (indexPath.section == 4){
        
        if (indexPath.row == 0) {
            isSel = !isSel;
            [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationFade];
        }else if (indexPath.row == 1){
            [self safeCompanyList];
        }
        
    }
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NSArray *titles = @[@"销售信息",@"付款类型",@"相关费用",@"客户信息",@"保险信息"];
    CarConfigHeaferView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    view.label.text = titles[section];
    view.rightImage.hidden = YES;
    if (view.gestureRecognizers == nil) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerViewClickedAction:)];
        [view addGestureRecognizer:tap];
    }
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 41;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
//    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
    
    
}
- (void) headerViewClickedAction:(UITapGestureRecognizer *)sender
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
    
}
//单个信息
-(void)creatChoose:(NSMutableArray *)titles tag:(NSInteger)tag{
    
    
    if (titles.count == 0) {
        [ShowMessage showHintMessage:@"暂无数据！" duration:2.0 withRemindId:remindWarning];
    }else{
        PickCustomView *pickerSingle = [[PickCustomView alloc]init];
        pickerSingle.tag = tag;
        pickerSingle.pickerViewHeight = 300;
        [pickerSingle setDataArray:titles];
        [pickerSingle setDefalutSelectRowStr:titles[0]];
        [pickerSingle setDelegate:self];
        [pickerSingle show];
        [self.view endEditing:YES];
    }
}
-(void)customPickView:(PickCustomView *)customPickView selectedTitle:(NSString *)selectedTitle index:(NSInteger)index{
    NSLog(@"选择%@",selectedTitle);
    if (customPickView.tag == 0) {
        _selaStr = selectedTitle;
        [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        
    }else if (customPickView.tag == 2){
        _peopleName = selectedTitle;
        UserModel *model = self.userArray[index];
        _peopleId = model.userId;
        
        [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        
    }else if (customPickView.tag == 3){
        _customer = selectedTitle;
        CustomersModel *model = self.customerArray[index];
        _customerId = model.channelId;
        [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationNone];
        
    }else if (customPickView.tag == 4){
        _company = selectedTitle;
        SafeCompanyModel *model = self.safeComArray[index];
        _companyID = model.insuranceId;
        [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationNone];
        
    }else if (customPickView.tag == 5){
        
        if ([selectedTitle isEqualToString:@"现金"]) {
            _isPayType = NO;
        }else if ([selectedTitle isEqualToString:@"按揭"]){
            _isPayType = YES;

        }
        
        [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
    }else if (customPickView.tag == 6){
        _mortgage = selectedTitle;
        MortgageCompanyModel *model = self.mortgageComArray[index];
        _mortgageId = model.mortgageId;
        
        [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];

    }
}
//时间
-(void)CreatDateChoose{
    
    isShowDay=YES;
    PickDateView *pickerDate = [[PickDateView alloc]init];
    pickerDate.pickerViewHeight = 300;
//    [pickerDate setIsAddYetSelect:YES];//是否显示至今选项
    [pickerDate setIsShowDay:isShowDay];//是否显示日信息
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [NSDate date];
    // 指定获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    NSDateComponents* comp = [gregorian components: unitFlags fromDate:dt];
    [pickerDate setDefaultTSelectYear:comp.year defaultSelectMonth:comp.month defaultSelectDay:comp.day];//设定默认显示的日期
    [pickerDate setDelegate:self];
    [pickerDate show];
}

-(void)pickerDateView:(BasePickView *)pickerDateView selectYear:(NSInteger)year selectMonth:(NSInteger)month selectDay:(NSInteger)day{
    NSLog(@"选择的日期是：%ld %ld %ld",year,month,day);
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [NSDate date];
    // 指定获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    // 获取不同时间字段的信息
    NSDateComponents* comp = [gregorian components: unitFlags
                                          fromDate:dt];
    if (isShowDay==YES) {
        if (year>comp.year) {
            _dateStr = @"至今";
        }else{
            _dateStr = [NSString stringWithFormat:@"%ld-%ld-%ld",year,month,day];
            
        }
    }else{
        if (year>comp.year) {
            _dateStr = @"至今";
        }else{
            _dateStr = [NSString stringWithFormat:@"%ld-%ld月",year,month];
        }
    }
    
    [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
    
}

//地址

-(void)chooseAdress{
    
    PickCityView *pickerArea = [[PickCityView alloc]init];
    pickerArea.pickerViewHeight = 300;
    [pickerArea setDelegate:self];
//    [pickerArea setDefaultCity:@"北京" DefaultProvience:@"北京"];
    [pickerArea show];
    [self.view endEditing:YES];
}

-(void)pickerArea:(PickCityView *)pickerArea selectProvince:(NSString *)province selectCity:(NSString *)city{
    NSLog(@"省市的选择%@ %@",province,city);
    _adress = [NSString stringWithFormat:@"%@  %@",province,city];
    _prevince = province;
    _city = city;
    [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationNone];
    
}
-(void)pickerArea:(PickCityView *)pickerArea selectProvinceId:(NSString *)provinceId selectCityId:(NSString *)cityId{
    _previnceId = provinceId;
    _cityId = cityId;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if (textField.tag == 31){
        _customName = text;
        if (text.length > 20) {
            return NO;
        }
    }else if (textField.tag == 3) {
        if ([DataCheck isLegalHXAccountCharacter:string] == NO) {
            if (string.length == 0) {
                _dealPrice = text;
                return YES;
            }
            return NO;
        }
        if ([text returnRealWithFloatLength:2] == YES) {
            _dealPrice = text;
        }
        return [text returnRealWithFloatLength:2];
    }else if (textField.tag == 4){
        _remarks = text;
    }else if (textField.tag == 30){
        
        _phoneNum = text;
        if (text.length > 11) {
            return NO;
        }
    }else if (textField.tag == 34){
        if ([DataCheck isLegalHKDemailCharacterRegister:string] == NO) {
            if (string.length == 0) {
                _Idcard = text;
                return YES;
            }
            return NO;
        }
        _Idcard = text;
        return [DataCheck isLegalHKDemailCharacterRegister:text];
    }else if (textField.tag == 42){
        if ([DataCheck isLegalHXAccountCharacter:text] == NO) {
            if (string.length == 0) {
                _business = text;
                return YES;
            }
            return NO;
        }
        if ([text returnRealWithFloatLength:2] == YES) {
            _business = text;
        }
        return [text returnRealWithFloatLength:2];

   }else if (textField.tag == 43){
       
       if ([DataCheck isLegalHXAccountCharacter:string] == NO) {
           if (string.length == 0) {
               _strong = text;
               return YES;
           }
           return NO;
       }
       if ([text returnRealWithFloatLength:2] == YES) {
           _strong = text;
       }
        return [text returnRealWithFloatLength:2];

    }else if (textField.tag == 11){
        if ([DataCheck isLegalHXAccountCharacter:string] == NO) {
            if (string.length == 0) {
                _orderPrice = text;
                return YES;
            }
            return NO;
        }
        if ([text returnRealWithFloatLength:2] == YES) {
            _orderPrice = text;
        }
        return [text returnRealWithFloatLength:2];

    }else if (textField.tag == 12){
        if ([DataCheck isLegalHXAccountCharacter:string] == NO) {
            if (string.length == 0) {
                _balance = text;
                return YES;
            }
            return NO;
        }
        if ([text returnRealWithFloatLength:2] == YES) {
            _balance = text;
        }
        return [text returnRealWithFloatLength:2];

    }else if (textField.tag == 13){
        if ([DataCheck isLegalHXAccountCharacter:string] == NO) {
            if (string.length == 0) {
                _firstPrice = text;
                return YES;
            }
            return NO;
        }
        if ([text returnRealWithFloatLength:2] == YES) {
            _firstPrice = text;
        }
        return [text returnRealWithFloatLength:2];

    }else if (textField.tag == 14){
        if ([DataCheck isLegalHXAccountCharacter:string] == NO) {
            if (string.length == 0) {
                _loanLimit = text;
                return YES;
            }
            return NO;
        }
        if ([text returnRealWithFloatLength:2] == YES) {
            _loanLimit = text;
        }
        return [text returnRealWithFloatLength:2];

    }else if (textField.tag == 15){
        if ([DataCheck isStringPureNumber:string] == NO) {
            if (string.length == 0) {
                _mortgageCyc = text;
                return YES;
            }
            return NO;
        }
//
        _mortgageCyc = text;
        return [DataCheck isStringPureNumber:text];
    }else if (textField.tag == 16){
        if ([DataCheck isLegalHXAccountCharacter:string] == NO) {
            if (string.length == 0) {
                _mortgagePrice = text;
                return YES;
            }
            return NO;
        }
        if ([text returnRealWithFloatLength:2] == YES) {
            _mortgagePrice = text;
        }
        return [text returnRealWithFloatLength:2];

    }else if (textField.tag == 17){
        if ([DataCheck isLegalHXAccountCharacter:string] == NO) {
            if (string.length == 0) {
                _deposit = text;
                return YES;
            }
            return NO;
        }
        if ([text returnRealWithFloatLength:2] == YES) {
            _deposit = text;
        }
        return [text returnRealWithFloatLength:2];

    }else if (textField.tag == 20){
        if ([DataCheck isLegalHXAccountCharacter:string] == NO) {
            if (string.length == 0) {
                _transferFee = text;
                return YES;
            }
            return NO;
        }
        if ([text returnRealWithFloatLength:2] == YES) {
            _transferFee = text;
        }
        return [text returnRealWithFloatLength:2];

    }else if (textField.tag == 21){
        if ([DataCheck isLegalHXAccountCharacter:string] == NO) {
            if (string.length == 0) {
                _commission = text;
                return YES;
            }
            return NO;
        }
        if ([text returnRealWithFloatLength:2] == YES) {
            _commission = text;
        }
        return [text returnRealWithFloatLength:2];

    }else if (textField.tag == 22){
        if ([DataCheck isLegalHXAccountCharacter:string] == NO) {
            if (string.length == 0) {
                _billingCost = text;
                return YES;
            }
            return NO;
        }
        if ([text returnRealWithFloatLength:2] == YES) {
            _billingCost = text;
        }
        return [text returnRealWithFloatLength:2];

    }else if (textField.tag == 23){
        if ([DataCheck isLegalHXAccountCharacter:string] == NO) {
            if (string.length == 0) {
                _otherCost = text;
                return YES;
            }
            return NO;
        }
        if ([text returnRealWithFloatLength:2] == YES) {
            _otherCost = text;
        }
        return [text returnRealWithFloatLength:2];

    }
    return YES;
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
    return YES;
    
}

-(void)rightItemClick{
    
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
    [self submitOrderInfo];
}

#pragma mark 键盘出现
-(void)keyboardWillShow:(NSNotification *)note
{
    CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.tableview.contentInset = UIEdgeInsetsMake(0, 0, keyBoardRect.size.height, 0);
}
#pragma mark 键盘消失
-(void)keyboardWillHide:(NSNotification *)note
{
    self.tableview.contentInset = UIEdgeInsetsZero;
}



//获取员工
-(void)LoadStaffInfo{
    
    
    NSDictionary *params = @{@"shopId":self.infomodel.result.shopId,
                             @"marketId":self.infomodel.result.marketId
                             };
    [SVProgressHUD show];
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",Api,staffInfoApi] refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        [self.userArray removeAllObjects];
        if ([response[@"code"] isEqual:@1]) {
            NSArray *array = response[@"result"];
            NSMutableArray *userNames= [[NSMutableArray alloc] init];
            for (NSDictionary *dic  in array) {
                UserModel *model = [[UserModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.userArray addObject:model];
                [userNames addObject:model.userName];
                
            }
            [self creatChoose:userNames tag:2];
        }
        [SVProgressHUD dismiss];
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        [SVProgressHUD dismiss];
        
    }];
    
}

//客户来源

-(void)loadCustomers{
    
    NSString *url = [NSString stringWithFormat:@"%@%@",CRMContextApi,customersApi];
    
    NSDictionary *dict = @{@"marketId":[NRWCarUser sharedUser].marketId,
                           @"shopId": [NRWCarUser sharedUser].shopId,
                           @"channelState": @1
                           };
    
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:dict progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        [self.customerArray removeAllObjects];
        NSMutableArray *customerName = [NSMutableArray array];
       
        if ([response[@"code"] isEqual:@1]) {
            
            NSArray *array = response[@"result"];
            for (NSDictionary *dic in array) {
                CustomersModel *model = [[CustomersModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.customerArray addObject:model];
                [customerName addObject:model.channelName];
                
            }
            [self creatChoose:customerName tag:3];
            
            
            
        }
        
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];

    }];
}

//保险公司列表
-(void)safeCompanyList{
    NSString *url = [NSString stringWithFormat:@"%@%@",CRMContextApi,safrCompanyApi];
    
    
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        
        if ([response[@"code"] isEqual:@1]) {
            NSArray *array = response[@"result"];
            NSMutableArray *safeCNames = [[NSMutableArray alloc] init];
            for (NSDictionary *dic in array) {
                
                SafeCompanyModel *model = [[SafeCompanyModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.safeComArray addObject:model];
                [safeCNames addObject:model.insuranceName];
                
            }
            [self creatChoose:safeCNames tag:4];
            
            
            
        }
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];

    }];
    
    
}

//按揭公司
-(void)laodMortgageList{
    
    NSString *url = [NSString stringWithFormat:@"%@%@",CRMContextApi,mortgageApi];
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if ([response[@"code"] isEqual:@1]) {
            NSArray *array = response[@"result"];
            [self.mortgageComArray removeAllObjects];
            NSMutableArray *mortNames = [[NSMutableArray alloc] init];
            for (NSDictionary *dic in array) {
                MortgageCompanyModel *model = [[MortgageCompanyModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.mortgageComArray addObject:model];
                [mortNames addObject:model.mortgageName];
            }
            [self creatChoose:mortNames tag:6];

        }

    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];

    }];
}

//数据提交

//提交信息
-(void)submitOrderInfo{
    
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,outLibaryApi];
    

    if ([_dateStr isEqualToString:@""]) {
        [ShowMessage showHintMessage:@"请输入成交日期!" duration:2.0 withRemindId:remindWarning];

        return;
    }

    NSInteger type = 1;
    if (_isPayType == YES) {
        //按揭
        type = 2;
    }else{
         type = 1;
    }
    if ([_dealPrice isEqualToString:@""]) {
        [ShowMessage showHintMessage:@"请填写成交价格!" duration:2.0 withRemindId:remindWarning];

        return;

    }
    
    NSInteger selaType = 0;
    if ([_selaStr isEqualToString:@"批发"]) {
        selaType = 1;
    }else if ([_selaStr isEqualToString:@"直销"]) {
        selaType = 2;
    }if ([_selaStr isEqualToString:@"拍卖"]) {
        selaType = 3;
    }if ([_selaStr isEqualToString:@""]) {
        [ShowMessage showHintMessage:@"请输入销售类型!" duration:2.0 withRemindId:remindWarning];

        return;
        
    }
    if ([_peopleId isEqualToString:@""]) {
        [ShowMessage showHintMessage:@"请输入成交员工!" duration:2.0 withRemindId:remindWarning];

        return;
    }
    
    NSDictionary *params = @{
                             @"userId":[NRWCarUser sharedUser].userId,
                             @"carId":self.infomodel.result.carId,
                             @"channelId":_customerId,
                             @"cityId":_cityId,
                             @"provinceId":_previnceId,
                             @"saleBalance":_balance,
                             @"saleBillPrice":_billingCost,
                             @"saleBusinessInsurPrice":_business,
                             @"saleBuyerCardNo":_Idcard,
                             @"saleBuyerMobile":_phoneNum,
                             @"saleBuyerName":_customName,
                             @"saleCommission":_commission,
                             @"saleDealDate":_dateStr,
                             @"saleDealUserId":_peopleId,
                             @"saleDeposit":_orderPrice,
                             @"saleFirstPayment":_firstPrice,
                             @"saleForceInsurPrice":_strong,
                             @"saleInsuranceCompany":_company,
                             @"saleInsuranceState":@(isSel),
                             @"saleLoanLimit":_loanLimit,
                             @"saleMortgageCycle":_mortgageCyc,
                             @"saleMortgageDeposit":_deposit,
                             @"saleMortgageName":_mortgage,
                             @"saleMortgagePrice":_mortgagePrice,
                             @"saleOtherPrice":_otherCost,
                             @"salePayType":@(type),
                             @"salePrice":_dealPrice,
                             @"saleRemark":_remarks,
                             @"saleTransferFee":_transferFee,
                             @"saleType":@(selaType)
                             };
    
    [YQNetworking postWithUrl:url refreshRequest:YES cache:NO params:params progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        if ([response[@"code"] isEqual:@1]) {
            [ShowMessage showHintMessage:@"出库成功!" duration:2.0 withRemindId:remindSuccess];
            NSNotification *notificatiom = [NSNotification notificationWithName:@"FactorySuccess" object:self.selIndex userInfo:nil];
            [[NSNotificationCenter defaultCenter] postNotification:notificatiom];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [ShowMessage showHintMessage:response[@"msg"] duration:2.0 withRemindId:remindFail];

        }
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];

    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
